Page({
  data: {
    starValue: 0,
    content: '',
    userInfo: null,
    id: 0,
    cid: 0,
    isLogin: false,
    submitting: false
  },

  // 输入评价内容时触发
  onContentInput(e) {
    this.setData({
      content: e.detail.value
    });
  },

  // 星级评分改变时触发
  onStarChange(e) {
    this.setData({
      starValue: e.detail
    });
  },

  // 提交评价
  onSubmit() {
    const { content, starValue, id, cid } = this.data;
    
    // 验证评价内容
    if (!content.trim()) {
      wx.showToast({
        title: '请填写评价内容',
        icon: 'none'
      });
      return;
    }

    // 验证评分
    if (starValue <= 0) {
      wx.showToast({
        title: '请给出评分',
        icon: 'none'
      });
      return;
    }

    // 设置为提交中状态
    this.setData({ submitting: true });

    // 格式化当前时间
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const evaluateTime = `${year}-${month}-${day}`;

    // 构建请求数据（完全匹配Apifox测试格式）
    const requestData = {
      courseId: parseInt(cid),
      content: content,
      score: parseFloat(starValue),
      evaluateTime: evaluateTime,
      userId: parseInt(id),
      course: {
        id: parseInt(cid)
      }
    };

    console.log('请求数据:', requestData);

    // 发送请求
    wx.request({
      url: 'http://localhost:8080/courseEvaluate',
      method: 'POST',
      data: requestData,
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('请求成功响应:', res);
        
        if (res.statusCode === 200) {
          // 检查服务器返回的数据
          if (res.data && res.data.success !== undefined) {
            if (res.data.success) {
              wx.showToast({
                title: '评价提交成功',
                icon: 'success'
              });
              setTimeout(() => {
                wx.navigateBack({ delta: 1 });
              }, 1500);
            } else {
              wx.showToast({
                title: res.data.message || '评价提交失败',
                icon: 'none'
              });
            }
          } else {
            // 兼容不同的服务器返回格式
            wx.showToast({
              title: '评价提交成功',
              icon: 'success'
            });
            setTimeout(() => {
              wx.navigateBack({ delta: 1 });
            }, 1500);
          }
        } else {
          wx.showToast({
            title: `提交失败: ${res.statusCode}`,
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      },
      complete: () => {
        // 无论成功或失败，都重置提交状态
        this.setData({ submitting: false });
      }
    });
  },

  onLoad(options) {
    // 获取课程ID
    if (options.cid) {
      this.setData({ cid: parseInt(options.cid) });
    } else {
      wx.showToast({ title: '课程信息获取失败', icon: 'none' });
      setTimeout(() => wx.navigateBack({ delta: 1 }), 1500);
      return;
    }

    // 验证登录状态
    const app = getApp();
    const globalUserInfo = app.globalData.loginUserInfo;
    if (!globalUserInfo || !globalUserInfo.id) {
      this.setData({ isLogin: false });
      wx.showModal({
        title: '未登录',
        content: '请先登录后再评价',
        showCancel: false,
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({ url: '/pages/login/login' });
          }
        }
      });
      return;
    }

    this.setData({
      userInfo: globalUserInfo,
      id: parseInt(globalUserInfo.id),
      isLogin: true
    });
  }
});